<?php

namespace app\admin\controller;

use app\admin\model\CaseClassification;
use app\admin\model\Config;
use app\admin\model\Drawing;
use app\admin\model\DrawingCase;
use app\admin\model\Substation;

/**
 * 案例管理
 * Class Cases
 * @package app\admin\controller
 */
class Cases extends Base
{

    //案例分类列表
    public function casesClassificationList(){
        $keyword = input("keyword/s");
        if(input("?table")) {
            $CaseClassification = new CaseClassification();
            $result["code"] = 0;
            $result["data"] = $CaseClassification->classificationList($keyword);
            $result["data"] = collection($result["data"])->toArray();
            if(empty($keyword)) {//搜索不保持树结构
                $result["data"] = Menus::arrayToTree($result["data"],0,0,"classification_id");
            }
            return json($result);
        }
        return view('casesClassificationList',[
            'title'         =>  '案例分类列表',
        ]);
    }

    //添加修改案例分类
    public function classificationAdd(){
        $classification_id = input("classification_id/d",0);
        $CaseClassification = new CaseClassification();
        if(request()->isPost()){
            $data = input("post.");
            $msg = $CaseClassification->checkData($data, [
                ["classification_name", "require", "分类名称不能为空"],
                ["substation_id", "require", "请选择发布网站"],
            ]);
            if ($msg === true) {
                if($CaseClassification->checkPKFieldOnly("classification_name",$data["classification_name"],$classification_id,$data["substation_id"])){
                    $result["code"] = 1;
                    $result["msg"] = '分类名称已存在';
                }else {
                    if ($CaseClassification->checkSave($classification_id,$data["substation_id"])) {
                        $Substation = new Substation();//分站类
                        $data["substation_name"] = $Substation->getFieldValue("substation_id", $data["substation_id"], "substation_name");
                        if ($CaseClassification->mySave($data, "classification_id", $classification_id)) {
                            if (!empty($classification_id)) {
                                //修改案例表分类名称
                                $DrawingCase = new DrawingCase();
                                $DrawingCase->setFieldValue("classification_id", $classification_id, "classification_name", $data["classification_name"]);
                            }
                            $result["code"] = 0;
                            $result["msg"] = "操作成功！";
                        } else {
                            $result["code"] = 10000;
                            $result["msg"] = "操作失败！";
                        }
                    }else{
                        $result["code"] = 20000;
                        $result["msg"] = "没有权限操作！";
                    }
                }
            }else {
                $result["code"] = 1;
                $result["msg"] = $msg;
            }
            return json($result);
        }
        if(!empty($classification_id)){
            //修改获取详情
            $dataInfo = $CaseClassification->PkInfo($classification_id);
            $this->assign('dataInfo',$dataInfo);
        }
        $classificationList = $CaseClassification->classificationList();
        $classificationList = Menus::arrayToTree(collection($classificationList)->toArray(),0,0,"classification_id");
        $Substation = new Substation();//分站类
        $userSubstationList = $Substation->userList();//获取分站集合
        $this->assign('userSubstationList',$userSubstationList);
        return view('classificationAdd',[
            'title'                     =>  '添加修改案例分类',
            'classificationList'         =>  $classificationList,
            'RadioIs'                   =>  config("IsNoRadio"),//获取Radio配置
        ]);
    }

    //删除案例分类
    public function classificationDel(){
        $classification_id = input("classification_id/d",0);
        $CaseClassification = new CaseClassification();
        if(!empty($classification_id)){
            $informationNumber = $CaseClassification->getInformationNumber($classification_id);
            if(!$informationNumber) {//查看该分类是否有案例
                if($CaseClassification->PKDel($classification_id,true)){//查看是否有子级分类
                    $result["code"] = 0;
                    $result["msg"] = "操作成功!";
                }else{
                    $result["code"] = 10001;
                    $result["msg"] = "操作失败，有子分类的上级分类不能直接删除!";
                }
            }else{
                $result["code"] = 10000;
                $result["msg"] = "该分类下有（".$informationNumber."）篇案例不能直接删除！";
            }
        }else{
            $result["code"] = 1;
            $result["msg"] = "classification_id参数为空!";
        }
        return json($result);
    }


    //案例列表
    public function caseList(){
        $keyword = input('keyword');//关键字
        $orderField = input('orderField');//关键字
        $orderType = input('orderType');//关键字
        $DrawingCase = new DrawingCase();
        if (input('?table')) {//是否表格请求
            $result["code"] = 0;
            $result['data'] = $DrawingCase->drawingList($keyword,$orderField,$orderType);
            $result['count'] = $DrawingCase->drawingListCount($keyword);
            return json($result);
        }
        return view('caseList',[
            'keyword'   => $keyword,
            'title'     =>  '案例列表',
        ]);
    }

    //添加编辑案例
    public function caseAdd(){
        $case_id = input("case_id/d",0);
        $DrawingCase = new DrawingCase();
        if(request()->isPost()){
            //发布案例
            $data = input("post.");
            $msg = $DrawingCase->checkData($data, [
                ["title", "require", "案例标题不能为空"],
                ["text_content", "require", "案例正文内容不能为空"],
                ["classification_id", "require", "案例分类不能为空"],
                ["drawing_id", "require", "关联图纸不能为空"],
                ["substation_id", "require", "请选择发布网站"],
            ]);
            if ($msg === true) {
                if ($DrawingCase->checkPKFieldOnly("title", $data["title"],$case_id, $data["substation_id"])) {
                    $result["code"] = 1;
                    $result["msg"] = "案例标题已存在";
                } else {
                    if ($DrawingCase->checkClassification($data["classification_id"],$data["substation_id"])) {
                        if ($DrawingCase->checkSave($case_id,$data["substation_id"])) {
                            if(empty($case_id)){
                                //添加
                                $data["atlas"] = !empty($data["atlas"]) ? json_encode($data["atlas"]) : json_encode([]);
                            }
                            if ($DrawingCase->mySave($data, "case_id", $case_id)) {
                                $result["code"] = 0;
                                $result["msg"] = "操作成功!";
                            } else {
                                $result["code"] = 10000;
                                $result["msg"] = "操作失败！";
                            }
                        }else{
                            $result["code"] = 20000;
                            $result["msg"] = "没有权限操作！";
                        }
                    }else{
                        $result["code"] = 30000;
                        $result["msg"] = "发布的网站不存在该案例分类！";
                    }
                }
            } else {
                $result["code"] = 1;
                $result["msg"] = $msg;
            }
        }else{//发布之前准备
            if(!empty($case_id)) {
                $dataInfo = $DrawingCase->PkInfo($case_id);//获取库案例信息
                $this->assign("dataInfo", $dataInfo);
            }
            $CaseClassification = new CaseClassification();
            $classificationList = $CaseClassification->classificationList();
            $classificationList = Menus::arrayToTree(collection($classificationList)->toArray(),0,0,"classification_id");
            $this->assign("classificationList", $classificationList);
            $Substation = new Substation();//分站类
            $userSubstationList = $Substation->userList();//获取分站集合
            $this->assign('userSubstationList',$userSubstationList);
        }
        return !empty($result) ? json($result) : view('caseAdd',[
            'title'                 =>  '添加编辑案例',
            'RadioIs'               =>  config("IsNoRadio"),//获取Radio配置
            'ueditor'               =>  true,
        ]);
    }

    //删除案例
    public function caseDel(){
        $case_id = input("case_id/d",0);
        $DrawingCase = new DrawingCase();
        if(!empty($case_id)){
            if($DrawingCase->PKDel($case_id,true)){
                $result["code"] = 0;
                $result["msg"] = "操作成功!";
            }else{
                $result["code"] = 10000;
                $result["msg"] = "操作失败！";
            }
        }else{
            $result["code"] = 1;
            $result["msg"] = "drawing_id，参数为空!";
        }
        return json($result);
    }

    //选择图纸
    public function choiceDrawing(){
        $keyword = input('keyword');//关键字
        if (input('?table')) {//是否表格请求
            $Drawing = new Drawing();
            $result['code'] = 0;
            $result['data'] = $Drawing->drawingList($keyword,"","");
            $result['count'] = $Drawing->drawingListCount($keyword,"","");
            return json($result);
        }
        $Config = new Config();
        return view('choiceDrawing',[
            'keyword'           => $keyword,
            'DrawingProgramme'  => $Config->getConfigTypeListArray("DrawingProgramme"),
            'DrawingType'       => $Config->getConfigTypeListArray("DrawingType"),
            'title'             =>  '选择图纸',
        ]);
    }

    //上传案例图集
    public function uploadCasesAtlas(){
        $drawing_id = input("drawing_id");//获取图纸ID
        $type = input("type");//上传类型
        if(!empty($drawing_id)){
            \think\Config::load(APP_PATH.'extra/upload.php');//加载上传配置文件
            $UploadFileConfig = \think\Config::get("UploadFileConfig");//获取配置
            if(!empty($UploadFileConfig[$type])) {//验证上传类型是否存在
                $Drawing = new Drawing();
                $drawingInfo = $Drawing->PkInfo($drawing_id);
                $UploadFileConfig[$type]["path"] .=  $drawingInfo["substation_id"] . "/" . $drawingInfo["no"] . "_" . $drawingInfo["no2"] .config("cases").($type == "CaseThumbnail" ? config("thumbnail") : config("atlas")) . "/";//添加图纸文件夹名称
                $data = ["", "array", $UploadFileConfig[$type]];
                $rs = action('FileOperation/uploadImg', $data);//上传图片
                $result = $rs;
            }else{
                $result["code"] = 1;
                $result["msg"] = "上传类型不存在!";
            }
        }else{
            $result["code"] = 1;
            $result["msg"] = "请先选择关联图纸!";
        }
        return json($result);
    }

    //接口设计案例列表
    public function addDesignCase(){
        $keyword = input("keyword/s");
        if (input('?table')) {//是否表格请求
            $ImgApiData = config("ImgApiData");
            $result = file_get_contents(url($ImgApiData["ApiList"]["customCase"], [
                'token' => md5(md5($ImgApiData["key"]).date("Y-m-d")),
                'limit' => $this->after_limit,
                'page' => $this->after_page,
                'keyword'  =>  $keyword
            ], true, $ImgApiData["domain"]));
            $result = json_decode($result,true);
            $result["code"] = 0;
            return json($result);
        }
        return view('addDesignCase',[
            'title'         =>  '接口设计案例列表',
        ]);
    }

    //导入设计案例
    public function importDesignCase(){
        $new = [];//新的数组集合
        set_time_limit(0);// 通过set_time_limit(0)可以让程序无限制的执行下去
        $data = input("post.data/a");
        $DrawingCase = new DrawingCase();
        $count = 0;//添加个数
        foreach ($data as $key=>$val){
            $msg = $DrawingCase->checkData($val, [
                ["project_no", "require", "编号不能为空"],
            ]);
            //去掉不符合条件和已存在的
            if($msg === true){
                $Drawing = new Drawing();
                $drawing_id = $Drawing->getFieldValue("no",$val["project_no"],"drawing_id");//查看图纸是否存在
                if(!empty($drawing_id)){
                    $substation_id = !empty($this->substations) ? $this->substations : config("importDesignCase")["substation_id"];//设置站点id
                    if(!$DrawingCase->getFieldCount("drawing_id",$drawing_id,$substation_id)) {//检查是否存在
                        $CaseClassification = new CaseClassification();
                        $classification_id = $CaseClassification->getFieldValue("classification_name", config("importDesignCase")["classification_name"], "classification_id", $substation_id);//获取分类id
                        if (!empty($classification_id)) {
                            $new[$key]["classification_id"] = $classification_id;//获取分类id
                            $new[$key]["substation_id"] = $substation_id;//获取网站id
                            $new[$key]["drawing_id"] = $drawing_id;//获取图纸id
                            $new[$key]["text_content"] = $val["demand"];//获取设计需求
                            $new[$key]["sheng"] = $val["bud_shen"];//获取设计需求
                            $new[$key]["shi"] = $val["bud_shi"];//获取设计需求
                            $new[$key]["xian"] = $val["bud_xian"];//获取设计需求
                            $new[$key]["title"] = mb_substr($val["user_name"], 0, 1, 'utf-8')."总的设计案例";//获取设计需求
                            $new[$key]["atlas"] = $val["refer"];//获取图集
                            $count++;
                        }
                    }
                }
            }
        }
        $new = $this->setAtlas($new);
        if($count > 0) {
            if ($DrawingCase->mySaveAll($new)) {
                $result["code"] = 0;
                $result["msg"] = "操作成功,添加成功（" . ($count) . "）个！";
            } else {
                $result["code"] = 10000;
                $result["msg"] = "操作失败!";
            }
        }else{
            $result["code"] = 10000;
            $result["msg"] = "没有符合条件的案例!";
        }
        return json($result);
    }

    //获取图集
    private function setAtlas($data){
        $FileOperation = new FileOperation();
        $ImgApiData = config("ImgApiData");//获取配置
        foreach ($data as $key=>$val) {
            if (!empty($val['atlas'])) {
                $temp = explode(",",$val["atlas"]);//获取
                $new = [];
                foreach ($temp as $tkey=>$tval){
                    $Drawing = new Drawing();
                    $info = $Drawing->PkInfo($val["drawing_id"]);
                    //下载封面缩略图到服务器
                    $fileResult = $FileOperation->downloadFile($ImgApiData['domain'] . $tval, "", config("drawingBankFileDefaultDir") .$val["substation_id"]."/" . $info["no"] . "_" . $info["no2"] .config("cases") . "/");
                    if ($fileResult['state']) {
                        $new[$tkey]["url"] = "/" . $fileResult['SaveName'];
                        $new[$tkey]["name"] = "";
                    }
                }
                if(!empty($new)) {
                    $data[$key]["atlas"] = $new;
                }else{
                    $data[$key]["atlas"] = [];
                }
            }else{
                $data[$key]["atlas"] = [];
            }
        }
        return $data;
    }
}
